package com.webex.ta.hydra;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.StringTokenizer;

/**
 * Created by Cisco WebEx.
 * User: vegaz
 * Date: 2010-8-13
 * Time: 15:28:14
 */
public class HydraStartup {

    private static CoreClassLoader loader = CoreClassLoader.getInstance();

    private static String hydraDir = null;

    public static String getHydraDir() {
        if (hydraDir == null) {
            String cp = System.getProperty("java.class.path");

            // Find Hydra home dir
            StringTokenizer tok = new StringTokenizer(cp, File.pathSeparator);
            if (tok.countTokens() == 1
                    || (tok.countTokens() == 2
                    && System.getProperty("os.name").toLowerCase().startsWith("mac os x")
            )
                    ) {
                File jar = new File(tok.nextToken());
                try {
                    hydraDir = jar.getCanonicalFile().getParentFile().getParent();
                } catch (IOException e) {
                    // ignore
                }
            } else {// e.g. started from IDE with full classpath
                hydraDir = System.getProperty("hydra.home", "");// Allow override
                if (hydraDir.length() == 0) {
                    File userDir = new File(System.getProperty("user.dir"));
                    hydraDir = userDir.getAbsoluteFile().getParent();
                }
            }
        }
        return hydraDir;
    }

    public static void main(String args[]) {
        Thread.currentThread().setContextClassLoader(loader);
        try {
            Class hydra = loader.loadClass("com.webex.ta.hydra.Hydra");

            Object instance = hydra.newInstance();
            Method startup = hydra.getMethod("start", new Class[]{(new String[0]).getClass()});
            startup.invoke(instance, new Object[]{args});
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(1);
        }
    }


    public static ClassLoader getClassLoader() {
        return loader;
    }
}
